<?php

namespace App\Http\Middleware;

use App\Exceptions\ParamsException;
use Closure;
use Validator;

class Validate
{
    /**
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     * @throws ParamsException
     */
    public function handle($request, Closure $next)
    {
        if (!isset($request->route()->action['controller']))
            return $next($request);
        $full = $request->route()->action['controller'];
        if ($array = $this->validateExits($full))
        {
            $validator = Validator::make($request->all(),$array['rules'],empty($array['messages'])?[]:$array['messages']);
            if ($validator->fails())
            {
                throw new ParamsException($validator->errors()->first());
            }
        }

        return $next($request);
    }

    /**
     * @param string $full
     * @return mixed
     */
    private function validateExits($full)
    {
        $path = str_replace('Http\Controllers','Validates',$full);
        list($class,$action) = explode('@',$path);

        if (class_exists($class) && in_array($action,get_class_methods($class)))
        {

            return (new $class())->$action();

        }
        return false;
    }
}
